<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<link rel="stylesheet" type="text/css"
	href="<%=basePath %>css/plugins/bootstrap-table/bootstrap-table.min.css">
<style>
.row{
	background-color: white;
	height: 100%
}
/* 阴影悬浮感觉 */
.divContainer {
	box-shadow: 2px 2px 5px #bbb;
}
/* 设置输入框样式 */
.personInfo{
	border-radius:5px;
	color:grey;
	text-align: center;
	width: 60%;
	height: 25px;
}
.form-row{
	margin-bottom: 15px
}
/* 设置所属部门栏鼠标样式 */
.roleControl:hover{
  cursor :not-allowed;
}
.roleControl{
	color:red
}

.opptionBtn{
	margin-bottom: 0px;	
	margin-top: 0px;
	margin-right: 0px
}
td {
	font-size: 10px;
	text-align: center;
}

th {
	font-size: 13px;
	text-align: center;
}
#query{
	position: absolute;
	left: 100px;
	top:10px;
	height: 40px;
	z-index: 999
}
.pagetitle{
	height: 50px;
	text-align: center;
	line-height:50px;
	font-size: 18px
}
#orgCode{
	font-size: 9px
}
#status{
	font-size: 9px
}
.flavr-prompt{
	color: gray;
}
</style>
<div class="row">
	<div class=" col-sm-12 pagetitle"><label>员工管理</label></div>
	<div class=" col-sm-12">
		<div class="row base-margin" id="query">
			<form class="form-inline" role="form"
				style="float: left; width: 100%" method="post" id="queryForm">
				<div class="form-group">
					<label for="orgCode">所属部门:</label> 
					<select class="form-control" id="orgCode" name="orgCode">
					</select>
				</div>
				<div class="form-group">
					<label for="status">当前状态:</label> 
					<select class="form-control" id="status" name="status">
						<option value="1">正常</option>
						<option value="2">已离职</option>
						<option value="3">请假中</option>
					</select>
				</div>
				<div class="form-group">
					<label for="userName">姓名:</label> <input type="text"
						class="form-control" name="userName" id="userName"
						placeholder="请输入名称">
				</div>
				<div class="form-group">
					<label for="tel">联系方式:</label> <input type="text"
						class="form-control" name="tel" id="tel"
						placeholder="请输入联系方式">
				</div>
				<div class="form-group">
					<button type="button" id="queryBtn" onclick="doQuery()"
						class="btn btn-success">查找</button>
				</div>
				<div class="form-group btn-right">
					<button type="button" class="btn btn-danger" id="addBtn"
						onclick="addUser()">添加新员工</button>
				</div>
			</form>
		</div>
		<div class="container  animated fadeInDown" style="width: 100%;">
			<table id="data-table">
			</table>
		</div>
	</div>
</div>
<script
	src="<%=basePath %>js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
<script
	src="<%=basePath%>js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
<script
	src="<%=basePath%>js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
<script>
function doQuery(){
	 $('#data-table').bootstrapTable('destroy');
	 initTable();
};
 
function initTable(){
	 var name = $('#userName').val();
	 var tel = $('#tel').val();
	 var roleId = $('#orgCode').val();
    $('#data-table').bootstrapTable({
        url: '<%=basePath%>Employee/getEmployeeList',
        dataField: "userList",//服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
        height: tableHeight(),//高度调整
        search: false,//是否搜索
        pagination: true,//是否分页
        pageSize: 10,//单页记录数
        pageList: [5, 10, 20, 30],//分页步进值
        sidePagination: "server",//服务端分页
        contentType: "application/x-www-form-urlencoded",//请求数据内容格式 默认是 application/json 自己根据格式自行服务端处理
        dataType: "json",//期待返回数据类型
        method: "POST",//请求方式
        searchAlign: "left",//查询框对齐方式
        queryParamsType: "",//查询参数组织方式
        queryParams: function getParams(params) {
            //params obj
			params.name = $('#userName').val();
            params.tel = $('#tel').val();
            params.roleId = $('#orgCode').val()==0?null:$('#orgCode').val();
            params.other = "otherInfo";
            params.status =  $('#status').val();
            return params;
        },
        showRefresh: true,//刷新按钮
        showColumns: true,//列选择按钮
        buttonsAlign: "right",//按钮对齐方式
        toolbar: "#toolbar",//指定工具栏
        toolbarAlign: "right",//工具栏对齐方式
        columns: [
            {
                field : 'id',
                title : '用户ID',
                align : 'center',
                valign : 'middle',
                sortable : true
            }, {
                field : 'realName',
                title : '姓名',
                align : 'center',
                valign : 'middle',
                sortable : true
            }, {
                field : 'sex',
                title : '性别',
                align : 'center',
                valign : 'middle'
            }, {
                field : 'tel',
                title : '联系方式',
                align : 'center',
                valign : 'middle',
                sortable : true
            }, {
                field : 'roles',
                title : '所属部门',
                align : 'center',
                valign : 'middle',
                sortable : true
            }, {
                field : 'createDate',
                title : '创建账号时间',
                align : 'center',
                valign : 'middle'
            }, {
                field : 'status',
                title : '当前状态',
                align : 'center',
                valign : 'middle'
            },{
                field : 'headImg',
                title : '头像地址',
                align : 'center',
                visible: false,
                valign : 'middle'
            },
            {
                field: "",
                title: "操作",
                formatter: operateFormatter,//对本列数据做格式化
            }],
        onClickRow: function(row, $element) {
          
        },//单击row事件
        locale: "zh-CN", //中文支持
    });
}
//根据窗口调整表格高度
$(window).resize(function() {
    $('#data-table').bootstrapTable('resetView', {
        height: tableHeight()
    })
})
 
 function addUser(){
	var checkObj =  $('#data-table').bootstrapTable('getAllSelections');
	var role =  $('#orgCode').val();
	var roleText =$('#orgCode').find("option:selected").text();
	var ids = [];
	if(checkObj.length==0){
		toastr.warning('请先选中您要授权的用户','警告');
		return false;
	}
	if (role==null){
		toastr.warning('请选择需要分配的部门','警告');
		return false;
	}
	$.confirm({
	    title: '确认分组',
	    content: '确认将选中用户分组至："'+roleText+'"?',
	    confirm: function(){
	    	$(checkObj).each(function(index,obj){
				  ids[index]=obj.id;
		 	});
			$.ajax({
				url:'<%=basePath%>Role/addUserRole',
				data:{'ids':ids,'roleId':role},
				type:'POST',
				dataType:'json',
				success:function(data){
					if (data.code=='200'){
						toastr.success(data.message,'成功');
						$('#data-table').bootstrapTable('refresh');
					}else{
						toastr.error(data.message,'操作失败');
					}
				},
				error:function(){
					toastr.error('服务器发烧了>_<,请稍后再试','网络异常');
				}
			});
	    },
	    cancel: function(){
	    	toastr.warning('已取消操作','已取消');
	    }
	});
}
 $(function() {
	 initTable();
	 $.ajax({
		 url:'<%=basePath%>Role/getAllRoles',
		 dataType:'JSON',
		 success:function(data){
			 var html = '<option value="0">默认分组</option>';
			 $(data.data).each(function(index,element){
				 html = html + '<option value="'+element.id+'">'+element.role+'</option>'
			 });
			 $('#orgCode').html(html);
		 }
	 })
	/*   
     $("#addRecord").click(function(){
         alert("name:" + $("#name").val() + " age:" +$("#age").val());
     }); */
 })

 function tableHeight() {
     return $(window).height() - 50;
 }
 function operateFormatter(value, row, index) {
     return [
    	 '<button class="btn btn-sm dim btn-info seeMore opptionBtn" onclick="seeMore(this)" title="查看" type="button"><i class="fa fa-paste"></i></button>',
    	 '<button class="btn btn-sm dim btn-success reset opptionBtn" onclick="reset(this)" title="登录密码重置" type="button"><i class="fa fa-reply"></i></button>',
    	 '<button class="btn btn-sm dim btn-warning del opptionBtn" title="离职" type="button"><i class="fa fa-remove"></i></button>'
     ].join('');
 }
/*  重置密码 */
function reset(obj){
	var tr = $(obj).parent().parent();
	var userId =  $(tr).find('td:nth-child(1)').text();
	new $.flavr({ 
		content : '重置密码',
		dialog : 'prompt',
        prompt : {
        	placeholder: '请输入6-11位密码' 
        }, 
        onConfirm : function( $container, $prompt){
        	var newPass = $prompt.val();
       		$.ajax({
				url:'<%=basePath%>Employee/modifyPass',
				data:{'id':userId,'newPass':newPass},
				type:'POST',
				dataType:'json',
				success:function(data){
					if (data.code=='200'){
						toastr.success(data.message,'成功');
					}else{
						toastr.error(data.message,'操作失败');
						return false;
					}
				},
				error:function(){
					toastr.error('服务器发烧了>_<,请稍后再试','网络异常');
					return false;
				}
       		});
        },
        onCancel : function(){ 
        	
        } 
    }); 
}
 
 
/**
 * 查看详情
 */
function seeMore(obj){
	var tr = $(obj).parent().parent();
	var userId =  $(tr).find('td:nth-child(1)').text();
	var nameTd = $(tr).find('td:nth-child(2)').text();
	var sexTd = $(tr).find('td:nth-child(3)').text();
	var telTd = $(tr).find('td:nth-child(4)').text();
	var roleTd = $(tr).find('td:nth-child(5)').text();
	if (sexTd=='男'){
		option = '<option style="text-align:center" value="男" selected="selected">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp男</option><option style="text-align:center" value="女">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp女</option>';
	}else{
		option = '<option style="text-align:center" value="男" >&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp男</option><option style="text-align:center" value="女" selected="selected">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp女</option>';
	}
	var html = ' <div class="form-row">'+
 	'<label for="userName">姓名：</label> <input class="personInfo" id="personUsername" type="text" name="username" value="'+nameTd+'"/>'+
    ' </div>' + 
    ' <div class="form-row">'+
    '<label for="sex">性别：</label>'+
    '<select class="personInfo" style="margin:0 auto" id="personSex" name="orgCode">'+option+
    '</select></div>'+
    ' <div class="form-row">'+
    '<label for="role">部门：</label><input class="personInfo roleControl" disabled="true" title="请在部门管理中编辑该员工所属部门" type="text" name="role" '+
    ' value="'+roleTd+'" />'+' </div>'+
    ' <div class="form-row">'+
    '<label for="tel">电话：</label> <input id="personTel" class="personInfo" type="text" name="tel" '+
    ' value="'+telTd+'" />'+' </div>';
	 new $.flavr({
		 title : nameTd, 
		 iconPath : '<%=basePath%>img/', 
		 icon : 'defultHead.png',
         content : html,
         animateEntrance:'flipInY',
         animateClosing:'rollOut',
         buttons : {
	       	 save : {
	       		 text: '保存',
	       		 style: 'success', 
	       		 action: function(){
	       			var  personUsername = $('#personUsername').val();
	       			if(personUsername==null|| $.trim(personUsername)==''){ 
		       			toastr.warning('请输入名称','错误');
		       	        return false; 
		       	    } 
	       			var  personSex = $('#personSex').val();
	       			var  personTel = $('#personTel').val();
		       		if(!(/^1[34578]\d{9}$/.test(personTel))){ 
		       			toastr.warning('手机号码有误，请重填','错误');
		       	        return false; 
		       	    }
		       		$.ajax({
						url:'<%=basePath%>Employee/modify',
						data:{'userName':personUsername,'tel':personTel,'sex':personSex,'id':userId},
						type:'POST',
						dataType:'json',
						success:function(data){
							if (data.code=='200'){
								toastr.success(data.message,'成功');
								setTimeout(function() {
									$('#data-table').bootstrapTable('refresh');
								}, 500);
							}else{
								toastr.error(data.message,'操作失败');
								return false;
							}
						},
						error:function(){
							toastr.error('服务器发烧了>_<,请稍后再试','网络异常');
							return false;
						}
		       		});
	      		}
	 		},
	 		cancel:{
	 			text: '取消',
	 			style:'default'
	 		}
	 	},
	 	
	 });
}
/**
 * 编辑单个员工
 */
function edit(obj){
	
	/*  var id = $(obj).attr('data');
	 var text = $('#role'+id).text();
	 $('#role'+id).html("<div class='tdbox'><div class='btnbox'><a id='"+id+"' style='color:green;margin-right:10px' onclick='editSave(this)'><i class='sunmit fa fa-check'></i></a><a style='color:red' data='"+text+"' onclick='editClose(this)'><i class='fa fa-close'></i></a></div><input class='form-control' data='"+id+" type='text' value='"+text+"'></input></div>"); */
}
/* window.operateEvents = {
     'click .seeMore': function (e, value, row, index) {
         console.log('查看'+ JSON.stringify(row))
     },
     'click .reset': function (e, value, row, index) {
    	 console.log(value)
      
     },
     'click .del': function (e, value, row, index) {
         console.log('删除'+ JSON.stringify(row))
     }
 }; */
function tableWidth() {
    return $(window).width() - 50;
}
</script>